package com.aispeech.asr.apis.ssc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;

import com.aispeech.asr.apis.ssc.data.form.CreateTaskForm;
import com.aispeech.asr.apis.ssc.service.TaskService;
import com.aispeech.asr.comm.data.vo.Result;
import com.aispeech.asr.webase.controller.Base;

import reactor.core.publisher.Mono;

@RestController
@CrossOrigin
@RequestMapping("/ssc-api/v1/task")
public class Task extends Base {
    @Autowired
    TaskService taskService;

    @PostMapping(value = "", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Mono<Result> create(ServerWebExchange exchange, @RequestParam("productId") String productId) {
        return exchange.getFormData()
                .map(MultiValueMap::toSingleValueMap)
                .flatMap(map -> CreateTaskForm.from(productId, map))
                .flatMap(taskService::create);
    }

    @GetMapping(value = "/{task_id}/progress")
    public Mono<Result> progress(@PathVariable("task_id") String taskId, @RequestParam("productId") String productId) {
        return taskService.progress(productId, taskId);
    }

    @GetMapping(value = "/{task_id}/result")
    public Mono<Result> result(@PathVariable("task_id") String taskId, @RequestParam("productId") String productId) {
        return taskService.result(productId, taskId);
    }
    
    @GetMapping(value = "/{task_id}/result/internal")
    public Mono<Result> internalResult(@PathVariable("task_id") String taskId, @RequestParam("productId") String productId) {
        return taskService.internalResult(productId, taskId);
    }
    
    @GetMapping(value = "/{task_id}/control")
    public Mono<Result> control(@RequestParam("act") String action, @RequestParam("task_id") String taskId) throws Exception {
        return taskService.doAction(action, taskId);
    }
}
